﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using fanfu.Common;
using fanfu.Business;
using fanfu.Model;
using System.IO;
using System.Configuration;

public partial class UploadFile : BasePage
{
    //所有文件信息
    private DataTable __UploadFile = new DataTable();

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string fileName = this.searchFileName.Value.Trim();
        string fileDes = this.searchFileDes.Value.Trim();
        string startTime = this.searchStartCreateTime.Value.Trim();
        string endTime = this.searchEndCreateTime.Value.Trim();
        byte fileType = byte.Parse(this.searchFileType.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        int parentId = int.Parse(this.searchParent.SelectedValue);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM UploadFile WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (fileName != "")
        {
            sqlString += "AND FileName like @FileName ";
            paraList.Add(new SqlParameter("@FileName", "%" + fileName + "%"));
        }
        if (fileDes != "")
        {
            sqlString += "AND FileDes like @FileDes ";
            paraList.Add(new SqlParameter("@FileDes", "%" + fileDes + "%"));
        }
        if (startTime != "")
        {
            sqlString += "AND CreateTime>=@StartCreateTime ";
            paraList.Add(new SqlParameter("@StartCreateTime", Convert.ToDateTime(startTime)));
        }
        if (endTime != "")
        {
            sqlString += "AND CreateTime<@EndCreateTime ";
            paraList.Add(new SqlParameter("@EndCreateTime", Convert.ToDateTime(endTime).AddDays(1)));
        }
        if (fileType != 0)
        {
            sqlString += "AND FileType=@FileType ";
            paraList.Add(new SqlParameter("@FileType", fileType));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        if (parentId != 0)
        {
            sqlString += "AND ParentId=@ParentId ";
            paraList.Add(new SqlParameter("@ParentId", parentId));
        }
        sqlString += "ORDER BY CreateTime DESC";
        #endregion

        //给数据列表赋值
        __UploadFile = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __UploadFile.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__UploadFile.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchFileName.Value = "";
        this.searchFileDes.Value = "";
        this.searchStartCreateTime.Value = "";
        this.searchEndCreateTime.Value = "";
        this.searchParent.SelectedIndex = 0;
        this.searchFileType.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __UploadFile = new UploadFileRule().GetAllFileInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __UploadFile.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__UploadFile.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定所有频道到下拉列表
    /// </summary>
    private void BindChannelList(DropDownList channelList)
    {
        string selectString = "SELECT * FROM Channel";
        DataTable systemMenu = SqlHelper.GetDataTable(selectString);
        if (systemMenu.Rows.Count > 0)
        {
            channelList.DataSource = systemMenu;
            channelList.DataTextField = "ChannelName";
            channelList.DataValueField = "ID";
            channelList.DataBind();
        }
        channelList.Items.Insert(0, new ListItem("全部频道", "0", true));
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.editSmallImagePath.Value = "";//清除缩略图值
        this.deleteID.Value = "";          //清除删除的ID
        this.editState.Value = "false";    //取消编辑状态
        RunJavascript("AddNew();", true);  //JS清空控件值
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定文件类型到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFileType, typeof(UploadFileType));
            //绑定文件状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(UploadFileFlag));
            //绑定所有顶级频道到下拉列表
            BindChannelList(this.searchParent);
            BindChannelList(this.drpParent);
            this.drpParent.Items.RemoveAt(0);
            //绑定列表并转到第一页
            BindAllData(this.rptDataList, 1);
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 编辑事件
    protected void lbtnEdit_Click(object sender, EventArgs e)
    {
        //设置编辑状态,选项卡跳转
        this.editState.Value = "true";
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            UploadFileModel uploadFile = new UploadFileRule().GetUploadFileByID(editID);

            //绑定值到页面控件
            this.txtFileName.Value = uploadFile.FileName;
            this.txtFileDes.Value = uploadFile.FileDes;
            this.txtCreator.Value = uploadFile.Creator;
            this.drpParent.ClearSelection();
            this.drpParent.Items.FindByValue(uploadFile.ParentId.ToString()).Selected = true;
            this.chkFlag.Checked = uploadFile.Flag == (byte)UploadFileFlag.normal ? true : false;
            this.imageFile.Src = uploadFile.SavePath;
            this.editSmallImagePath.Value = uploadFile.SmallImagePath;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new UploadFileRule().DeleteUploadFile(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        #region 获取控件值
        string fileName = this.txtFileName.Value.Trim();
        string fileDes = this.txtFileDes.Value.Trim();
        string creator = this.txtCreator.Value.Trim();
        if (creator == "") creator = CookieHelper.GetCookie("userAlias");
        byte uploadFileType = (byte)UploadFileType.otherType;
        int parentId = int.Parse(this.drpParent.SelectedItem.Value);
        string parentName = this.drpParent.SelectedItem.Text;
        byte flag = this.chkFlag.Checked == true ? (byte)ChannelFlag.normal : (byte)ChannelFlag.delete;
        DateTime createTime = DateTime.Now;
        string savePath = string.Empty;
        string smallImagePath = string.Empty; //缩略图

        //获取旧文件的地址
        string oldFilePath = savePath = this.imageFile.Src;
        string oldSmallImagePath = smallImagePath = this.editSmallImagePath.Value;
        #endregion

        #region 上传文件
        string fileUpName = this.fupFileName.FileName;
        try
        {
            if (fileUpName != "")
            {
                //配置文件没有设置时则设置默认路径
                string configPath = ConfigurationManager.AppSettings["UploadFilePath"];
                if (string.IsNullOrEmpty(configPath))
                    configPath = "~/Upload/UploadFile/";

                //物理路径不存在则创建物理路径
                string realityPath = Server.MapPath(configPath);
                if (!Directory.Exists(realityPath))
                    Directory.CreateDirectory(realityPath);

                FileInfo fileInfo = new FileInfo(fileUpName);
                string fileType = fileInfo.Extension.ToLower();

                bool isImageFile =".gif".Equals(fileType) || ".jpg".Equals(fileType) || ".bmp".Equals(fileType) || ".png".Equals(fileType);
                bool isRarFile = ".rar".Equals(fileType) || ".zip".Equals(fileType);
                bool isOtherFile = ".txt".Equals(fileType) || ".swf".Equals(fileType) || ".wmv".Equals(fileType) || ".avi".Equals(fileType) || ".wma".Equals(fileType) || ".mp3".Equals(fileType) || ".mid".Equals(fileType);

                #region 设置文件类型字段值
                //设置文件类型字段值
                if (isImageFile)
                {
                    uploadFileType = (byte)UploadFileType.imageType;
                }
                else if (isRarFile)
                {
                    uploadFileType = (byte)UploadFileType.rarType;
                    smallImagePath = "";
                }
                else
                {
                    uploadFileType = (byte)UploadFileType.otherType;
                    smallImagePath = "";
                }
                #endregion

                //文件类型是否正确
                if (isImageFile || isRarFile || isOtherFile)
                {
                    fileUpName = fileName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + "-" + fileUpName;
                    savePath = configPath + fileUpName;
                    this.fupFileName.SaveAs(realityPath + fileUpName);

                    //新文件上传成功后删除原来的旧文件
                    if (oldFilePath != "")
                    {
                        //解除缓存或目录被删除导致的错误
                        try { File.Delete(Server.MapPath(oldFilePath)); }
                        catch (Exception ex) { }
                    }

                    #region 如果是图片类型,则创建缩略图
                    //如果是图片类型,则创建缩略图
                    if (isImageFile)
                    {
                        //创建并保存缩略图
                        smallImagePath = CreateSmallImage(configPath, fileUpName, 150, 150);
                    }
                    #endregion

                    //上传新文件成功后删除原来的缩略图
                    if (oldSmallImagePath != "")
                    {
                        //解除缓存或目录被删除导致的错误
                        try { File.Delete(Server.MapPath(oldSmallImagePath)); }
                        catch (Exception ex) { }
                    }
                }
                else
                {
                    RunJavascript("PopupMsg('error','上传文件类型错误,请选择.gif,jpg,bmp,png,txt,rar,zip,swf,wmv,avi,wma,mp3,mid格式的文件！');", true);
                    RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            RunJavascript("PopupMsg('error','错误,文件上传失败！');", true);
            return;
        }
        #endregion

        //是否是修改状态
        if (this.editState.Value == "true")
        {
            string editID = this.editID.Value;
            #region 更新文件
            //更新文件
            List<SqlParameter> paraList = new List<SqlParameter>();
            string sqlString = "UPDATE UploadFile SET FileName=@FileName, FileDes=@FileDes, Creator=@Creator,"
                + " ParentId=@ParentId, ParentName=@ParentName, Flag=@Flag, SavePath=@SavePath, SmallImagePath=@SmallImagePath, CreateTime=@CreateTime WHERE ID=@ID";
            
            //判断是否修改了上传的文件
            if (string.IsNullOrEmpty(fileUpName))
            {
                sqlString = "UPDATE UploadFile SET FileName=@FileName, FileDes=@FileDes, Creator=@Creator, FileType=@FileType,"
                + " ParentId=@ParentId, ParentName=@ParentName, Flag=@Flag, SavePath=@SavePath, SmallImagePath=@SmallImagePath, CreateTime=@CreateTime WHERE ID=@ID";
                paraList.Add(new SqlParameter("@FileType", uploadFileType));
            }

            paraList.Add(new SqlParameter("@FileName", fileName));
            paraList.Add(new SqlParameter("@FileDes", fileDes));
            paraList.Add(new SqlParameter("@Creator", creator));
            paraList.Add(new SqlParameter("@ParentId", parentId));
            paraList.Add(new SqlParameter("@ParentName", parentName));
            paraList.Add(new SqlParameter("@Flag", flag));
            paraList.Add(new SqlParameter("@SavePath", savePath));
            paraList.Add(new SqlParameter("@SmallImagePath", smallImagePath));
            paraList.Add(new SqlParameter("@CreateTime", createTime));
            paraList.Add(new SqlParameter("@ID", editID));
            int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
            if (result == 1)
            {
                #region 手动级联更新
                //更新属于图片文件的评论
                string sqlUpdateReview = "UPDATE Review SET ParentName='" + fileName + "' WHERE ParentId=" + editID + " AND ParentType=" + (int)ReviewParentType.image;
                SqlHelper.ExecuteCommand(sqlUpdateReview);
                #endregion
                RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,更新失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
            #endregion
        }
        else
        {
            #region 新增文件
            //新增文件
            UploadFileModel uploadFile = new UploadFileModel();
            uploadFile.FileName = fileName;
            uploadFile.FileDes = fileDes;
            uploadFile.Creator = creator;
            uploadFile.FileType = uploadFileType;
            uploadFile.ParentId = parentId;
            uploadFile.ParentName = parentName;
            uploadFile.Flag = flag;
            uploadFile.SavePath = savePath;
            uploadFile.SmallImagePath = smallImagePath;
            uploadFile.CreateTime = createTime;
            int result = SqlHelper.ExecuteCommand(UploadFileModel.GetInsertSQL(), uploadFile.ToSqlParameters());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,新建成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,新建失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
            #endregion
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}